package com.grgbanking.it.system.component;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.grgbanking.it.common.HttpConnection;
import com.grgbanking.it.common.json.JSONConfigUtil;
import com.grgbanking.it.external.entity.Supplier;
import com.grgbanking.it.system.entity.Department;
import com.grgbanking.it.system.entity.User;
import com.grgbanking.it.system.entity.WXBatchUser;
import com.grgbanking.it.system.entity.WXDepartment;
import com.grgbanking.it.system.entity.WXUser;
import com.grgbanking.it.wx.common.Token;
import com.grgbanking.it.wx.common.WXConstant;

/**
 * 组织架构创建者
 * 包括部门及员工
 * 
 * WXOrganizationCreator
 * 
 * @author 潘广伟
 * @Email p_3er@qq.com
 * @Date 2014-11-7 上午9:03:47
 * 
 * @version 1.0.0
 *
 */
@Component
public class WXOrganizationCreator {
	@Autowired
	private HttpConnection httpConnection;
	
	
	
	public void setHttpConnection(HttpConnection httpConnection) {
		this.httpConnection = httpConnection;
	}

	/**
	 * 创建一个部门并返回部门id
	 * 
	 * @param department
	 * @return
	 * @throws Exception
	 */
	public WXDepartment createDepartment(Department department) throws Exception{
		StringBuffer url = new StringBuffer(WXConstant.DEPARTMENT_CREAT_URL).append(Token.getToken(httpConnection));

		WXDepartment wxDepartment = new WXDepartment(department);
		String content = JSONObject.fromObject(wxDepartment).toString();
		
		String responeText = httpConnection.sendPost(url.toString(), content);
		JSONObject obj = JSONObject.fromObject(responeText);

		wxDepartment.setWxId(obj.getInt("id"));
		return wxDepartment;
	}
	
	/**
	 * 更新部门
	 * updateDepartment
	 * 
	 * @param department
	 * @throws Exception 
	 * @exception 
	 * @since  1.0.0
	 */
	public void updateDepartment(Department department) throws Exception{
		StringBuffer url = new StringBuffer(WXConstant.DEPARTMENT_UPDATE_URL).append(Token.getToken(httpConnection));
		
		WXDepartment wxDepartment = new WXDepartment(department);
		String content = JSONObject.fromObject(wxDepartment).toString();
		
		String responeText = httpConnection.sendPost(url.toString(), content);
		System.out.println(responeText);
	}
	
	/**
	 * 获取用户ID
	 * getUserId
	 * 
	 * @param code
	 * @return
	 * @throws Exception 
	 * @exception 
	 * @since  1.0.0
	 */
	public String getUserId(String code,Integer agentId) throws Exception{
		StringBuffer url = new StringBuffer(WXConstant.USER_GET_URL);
		url.append("?access_token=").append(Token.getToken(httpConnection));
		url.append("&code=").append(code);
		url.append("&agentid=").append(agentId);
		
		String responeText = httpConnection.sendGet(url.toString());
		
		if(responeText.contains("errmsg")){
			return null;
		}else{
			JSONObject obj = JSONObject.fromObject(responeText);
			return obj.getString("UserId");
		}
	}
	
	/**
	 * 创建一个用户
	 * @param wxDepartmentId
	 * @param user
	 * @throws Exception
	 */
	public  String createUser(Integer wxDepartmentId,User user) throws Exception{
		StringBuffer url = new StringBuffer(WXConstant.USER_CREAT_URL).append(Token.getToken(httpConnection));
		
		WXUser wxUser = new WXUser(user, wxDepartmentId);
		String content = JSONObject.fromObject(wxUser,JSONConfigUtil.getNotEmptyConfig()).toString();
		
		String responeText = httpConnection.sendPost(url.toString(), content);
		System.out.println(responeText);
		return responeText;
	}
	
	/**
	 * 创建一个供应商
	 * createSupplier
	 * 
	 * @param supplier
	 * @return
	 * @throws Exception 
	 * @exception 
	 * @since  1.0.0
	 */
	public String createSupplier(Supplier supplier) throws Exception{
		StringBuffer url = new StringBuffer(WXConstant.USER_CREAT_URL).append(Token.getToken(httpConnection));
		
		WXUser wxUser = new WXUser(supplier);
		String content = JSONObject.fromObject(wxUser,JSONConfigUtil.getNotEmptyConfig()).toString();
		
		String responeText = httpConnection.sendPost(url.toString(), content);
		
		return responeText;
	}
	/**
	 * 批量删除用户
	 * deleteUsers
	 * 
	 * @param users
	 * @return
	 * @throws Exception 
	 * @exception 
	 * @since  1.0.0
	 */
	public String deleteUsers(List<WXUser> users) throws Exception{
		StringBuffer url = new StringBuffer(WXConstant.USER_BATCHDELETE_URL).append(Token.getToken(httpConnection));
		String[] useridlist = new String[users.size()];
		
		for(int i = 0; i < users.size(); i++){
			useridlist[i] = users.get(i).getUserid();
		}
		String content = JSONObject.fromObject(new WXBatchUser(useridlist)).toString();
		
		String responeText = httpConnection.sendPost(url.toString(), content);
		System.out.println(responeText);
		return responeText;
	}
	/**
	 * 删除部门及其子部门下所有的用户
	 * deleteUsersByDepartment
	 * 
	 * @param departmentId
	 * @return
	 * @throws Exception 
	 * @exception 
	 * @since  1.0.0
	 */
	public String deleteUsersByDepartment(Integer departmentId) throws Exception{
		return this.deleteUsers(this.getUsersByDepartmentId(departmentId));
	}
	
	/**
	 * 获取所有的微信部门列表
	 * getAllWXDepartment
	 * 
	 * @return
	 * @throws Exception 
	 * @exception 
	 * @since  1.0.0
	 */
	public List<WXDepartment> getAllWXDepartment() throws Exception{
		StringBuffer url = new StringBuffer(WXConstant.DEPARTMENT_LIST_URL).append(Token.getToken(httpConnection));

		String json = httpConnection.sendGet(url.toString());
		
		JSONObject obj = JSONObject.fromObject(json);
		List<WXDepartment> list = new ArrayList<WXDepartment>();
		
		if(obj.getString("errmsg").equals("ok")){
			JSONArray array = JSONArray.fromObject(obj.getString("department"));
			for (int i = 0; i < array.size(); i++) {
				
				WXDepartment department = (WXDepartment) JSONObject.toBean((JSONObject) array.get(i), WXDepartment.class);
				
				list.add(department);
			}
		}
		
		return list;
	}
	/**
	 * 获取部门下的所有微信用户
	 * getUsersByDepartmentId
	 * 
	 * @param departmentId
	 * @return
	 * @throws Exception 
	 * @exception 
	 * @since  1.0.0
	 */
	public List<WXUser> getUsersByDepartmentId(Integer departmentId) throws Exception{
		StringBuffer url = new StringBuffer(WXConstant.USER_LIST_URL).append(Token.getToken(httpConnection));
		url.append("&department_id=").append(departmentId);
		url.append("&fetch_child=1&status=0");
		
		
		List<WXUser> list = new ArrayList<WXUser>();
		String json = httpConnection.sendGet(url.toString());
		JSONObject obj = JSONObject.fromObject(json);
		if(obj.getString("errmsg").equals("ok")){
			JSONArray array = JSONArray.fromObject(obj.getString("userlist"));
			for (int i = 0; i < array.size(); i++) {
				WXUser user = (WXUser) JSONObject.toBean((JSONObject) array.get(i), WXUser.class);
				
				list.add(user);
			}
		}
		
		return list;
	}
	/**
	 * 删除部门
	 * delateDepartment
	 * 
	 * @param departmentId
	 * @return
	 * @throws Exception 
	 * @exception 
	 * @since  1.0.0
	 */
	public String deleteDepartment(Integer departmentId) throws Exception{
		StringBuffer url = new StringBuffer(WXConstant.DEPARTMENT_DELETE_URL).append(Token.getToken(httpConnection));
		url.append("&id=").append(departmentId);
		
		return httpConnection.sendGet(url.toString());
	}
	/**
	 * 删除子部门及孙部门
	 * deleteChildrenDepartment
	 * 
	 * @param parentId
	 * @throws Exception 
	 * @exception 
	 * @since  1.0.0
	 */
	public void deleteChildrenDepartment(Integer parentId) throws Exception{
		List<WXDepartment> list = getAllWXDepartment();
		List<WXDepartment> departments = getChildDepartment(parentId, list);
		for(WXDepartment department : departments){
			
			List<WXDepartment> children = this.getChildDepartment(parentId, list);
			if(children.size() > 0){
				deleteChildrenDepartment(department.getId());
			}
			String response = deleteDepartment(department.getId());
			System.out.println(response);
		}
	}
	/**
	 * 获取所有子部门	
	 * getChildDepartment
	 * 
	 * @param parentId
	 * @param list
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	public List<WXDepartment> getChildDepartment(Integer parentId,List<WXDepartment> list){
		List<WXDepartment> children = new ArrayList<WXDepartment>();
		for(WXDepartment d : list){
			if(d.getParentid().equals(parentId.toString())){
				children.add(d);
			}
		}
		return children;
	}
	
	public void yt() throws Exception{
		int parentId = 1829;
//		deleteUsersByDepartment(parentId);
		deleteChildrenDepartment(parentId);
		
	}
	
	
	
	public static void main(String[] args){
		WXOrganizationCreator creator = new WXOrganizationCreator();
		
		creator.setHttpConnection(new HttpConnection());
		try {
			creator.yt();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
